<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\rszs\controller;

use app\base\BaseController;
use app\cert\model\SecurityAccount;
use app\cert\model\SecurityAccountPayment;
use app\rszs\model\RszsLog;
use app\rszs\model\RszsLogDetail;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;
use think\facade\View;

class Rszs extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            $whereOr = array();


            $where[] = ['a.delete_time', '=', 0];

            $model = new RszsLog();
            $list = $model->get_list($param, $where, $whereOr);
            return table_assign(0, '', $list);
        } else {

            return view();
        }
    }

    //添加&&编辑
    public function add()
    {
        $param = get_params();
        $file = $_FILES['file'];

        //截取文件的后缀名，转化成小写
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if ($extension != "xlsx") {
            return to_assign(1, "模板格式错误！");
        }
        $spreadSheet = IOFactory::load($file['tmp_name']);//载入xlsx文件
        $sheet = $spreadSheet->getSheet(0);//根据表索引获取工作表
        $row_num = $sheet->getHighestRow(); //最大行数 19
        $col_num = $sheet->getHighestColumn(); //最大列数 C
        $data = []; //数组形式获取表格数据
        $head = [];
        for ($col = 'A'; $col <= 'N'; $col++) {
            //从第⼆⾏开始，去除表头（若⽆表头则从第⼀⾏开始）
            for ($row = 1; $row <= $row_num; $row++) {
                if ($row > 1) {
                    $data[$row - 2][] = $sheet->getCell($col . $row)->getValue();
                } else {
                    $head[] = $sheet->getCell($col . $row)->getValue();
                }
            }
        }
        if (count($head) < 14) {
            return to_assign(1, "模板错误");
        }
        $head_row = ['姓名', '证件号码', '单位名称', '社保编号', '性别', '失业保险参保时间', '失业保险应缴月数', '失业保险实缴月数', '失业保险欠费月数', '工伤保险参保时间', '工伤保险应缴月数', '工伤保险实缴月数', '工伤保险欠费月数', '过期时间'];
        foreach ($head_row as $k => $v) {
            if ($head[$k] != $v) {
                return to_assign(1, '模板错误！' . $head[$k]);
            }
        }
        $param['create_time'] = time();
        $param['admin_id'] = $this->uid;
        $param['number'] = count($data);
        $model = new RszsLog();
        $rszs_log_id = $model->field(true)->insertGetId($param);
        $all = self::handle_data($data,$rszs_log_id);
        if($rszs_log_id){
            $model_detail = new RszsLogDetail();
            $res = $model_detail->field(true)->insertAll($all);
            if($res){
                return to_assign(0, "导入成功");
            }else{
                return to_assign(1, "导入失败");
            }
        }
        return to_assign(1, "导入失败");
    }

    public static function handle_data($data,$rszs_log_id)
    {
        $all = [];
        foreach ($data as $item) {
            $values = [];
            $values['rszs_log_id'] = $rszs_log_id;
            $values['name'] = $item[0];
            $values['idcard'] = $item[1];
            $values['company'] = $item[2];
            $values['code'] = $item[3];
            $values['sex'] = $item[4];
            $values['sybx_insured_date'] = $item[5];
            $values['sybx_insured_yj_month'] = $item[6];
            $values['sybx_insured_sj_month'] = $item[7];
            $values['sybx_insured_qf_month'] = $item[8];
            $values['gsbx_insured_date'] = $item[9];
            $values['gsbx_insured_yj_month'] = $item[10];
            $values['gsbx_insured_sj_month'] = $item[11];
            $values['gsbx_insured_qf_month'] = $item[12];
            $values['create_time'] = time();
            $all[] = $values;
        }
        return $all;
    }

    //删除
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['delete_time'] = time();
            if (Db::name('rszs_log')->update($data) !== false) {
                Db::name('rszs_log_detail')->where('rszs_log_id',$id)->update(['delete_time'=>time()]);
                add_log('delete', $id);
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }


    //添加&&编辑
    public function detail()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $rszs_log_id = isset($param['rszs_log_id']) ? $param['rszs_log_id'] : 0;
            if ($rszs_log_id == 0) {
                return to_assign(1, "缺少参数");
            }
            $where = array();
            $where[] = ['a.delete_time', '=', 0];
            $where[] = ['a.rszs_log_id', '=', $rszs_log_id];
            $whereOr = [];

            $model = new RszsLogDetail();
            $list = $model->get_list($param, $where, $whereOr);
            $data['data'] = $list;
            return table_assign(0, '', $list);
        }else{
            $param = get_params();
            $rszs_log_id = isset($param['rszs_log_id']) ? $param['rszs_log_id'] : 0;
            View::assign('rszs_log_id', $rszs_log_id);
            return view();
        }
    }


    public function qrcode_create(){

        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;

        include 'phpqrcode.php';

        //生成二维码图片
        $errorCorrectionLevel = 'L';	//容错级别
        $matrixPointSize = 4;			//生成图片大小
        $file_path = 'qrcode/'.date('Ymd').mt_rand(1000,9999).'/';
        $path= root_path() .'public/storage/'.$file_path;
        if(!file_exists($path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path,0777,true);
        }

        $list =  Db::name('rszs_log_detail')->where('rszs_log_id',$id)->select()->toArray();
        $i=0;
        foreach ($list as $k => $v){
            $urlstr = 'http://sxrs.jzqygl.top'.'/home/rszs/information_insured_personnel?id='.$v['id'];
            $img = $v['name'].'.png';
            $filename = $path.$img;
            \QRcode::png($urlstr,$filename , $errorCorrectionLevel, $matrixPointSize, 4);
            $QR = $filename;				//已经生成的原始二维码图片文件
            $QR = imagecreatefromstring(file_get_contents($QR));
            //保存图片,销毁图形，释放内存
            if (!file_exists($filename)) {
                imagepng($QR, $filename);
                imagedestroy($QR);
            } else {
                $i++;
                Db::name('rszs_log_detail')->where('id',$v['id'])->update(['path'=>$filename]);
                imagedestroy($QR);
            }
        }

        if(count($list)==$i){
            Db::name('rszs_log')->where('id',$id)->update(['is_qrcode'=>'是']);
            return to_assign(0, "二维码已批量生成");
        }else{
            return to_assign(0, "生成失败");
        }
    }

    public function download(){
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        $zip = new \ZipArchive();
        $file_path = 'qrcode_zip/';
        $path= $file_path;
        if(!file_exists($path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path,0777,true);
        }
        $zipname= $path.date('Ymd').mt_rand(1000,9999).'.zip';
        //打开一个压缩文件，如果没则新建一个
        $zip->open($zipname, \ZipArchive::CREATE);

        $list =  Db::name('rszs_log_detail')->where('rszs_log_id',$id)->select()->toArray();
        foreach ($list as $k => $v){
            //添加一个文件到压缩
            $zip->addFile($v['path'],$v['name'].'.png');
        }
        $zip->close();
        //这里是下载zip文件
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zipname));
        header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");
        readfile($zipname);
        Db::name('rszs_log')->where('id',$id)->inc('download_num')->update();
        exit;
    }

}
